package ui.home.column2.channel_mapping.friends

import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.onPointerEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.hutool.core.util.IdUtil
import model.db.Db
import model.enums.ContentType
import model.enums.MenuItem
import model.vo.FriendsMappingItem
import model.vo.MessageContentItem
import model.vo.MessageListItem
import theme.EasyChatTheme
import ui.compose.NetworkImage
import ui.home.HomeViewModel
import ui.home.column2.message.MessageRow


/**
 * @author wei kunJie
 * @date 2024/3/25 14:47:57
 * 好友列表
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun FriendsMappingList(easyChatTheme: MutableState<EasyChatTheme>,modifier: Modifier, friendsMappingItems: MutableList<FriendsMappingItem>,viewModel: HomeViewModel) {
    val selectAccount = remember { mutableStateOf("") }
    val isActivityVerticalScrollbar = remember { mutableStateOf(false) }
    Box(modifier = modifier
        .onPointerEvent(PointerEventType.Enter) { isActivityVerticalScrollbar.value = true }
        .onPointerEvent(PointerEventType.Exit) { isActivityVerticalScrollbar.value = false }) {
        val state = rememberLazyListState()
        //渲染列表
        LazyColumn(modifier = Modifier.fillMaxSize(), state = state) {
            items(friendsMappingItems) { item ->
                if (viewModel.searchText.value == "") {
                    FriendsMappingRow(item = item, selectAccount = selectAccount, homeViewModel = viewModel, easyChatTheme =easyChatTheme )
                } else if (
                    item.account.contains(viewModel.searchText.value) ||
                    item.account.contains(viewModel.searchText.value)
                ) {
                    FriendsMappingRow(item = item, selectAccount = selectAccount, homeViewModel = viewModel, easyChatTheme = easyChatTheme)
                }
            }
        }
        //只有当鼠标进入时才出现滚动条
        if (isActivityVerticalScrollbar.value) {
            VerticalScrollbar(
                modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
                adapter = rememberScrollbarAdapter(
                    scrollState = state
                )
            )
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun FriendsMappingRow(easyChatTheme: MutableState<EasyChatTheme>,item: FriendsMappingItem, selectAccount: MutableState<String>,homeViewModel: HomeViewModel) {
    Box(
        modifier = Modifier.background(
            color = if (selectAccount.value == item.account) easyChatTheme.value.mainColor
            else Color.Transparent
        )
            .fillMaxWidth()
            .height(81.dp)
            .combinedClickable(
                onClick = {
                selectAccount.value = item.account
            },
                onDoubleClick = {
                    val existMessageListItem = homeViewModel.messageList.find { isExistIt ->
                        isExistIt.account == item.account && !isExistIt.isGroup
                    }
                    if (existMessageListItem == null) {//不存在，直接置顶
                        val messageListItem = MessageListItem(
                            id = IdUtil.getSnowflakeNextId(),
                            account = item.account,
                            headImage = item.headUrl,
                            title = item.userName,
                            time = "",
                            isGroup = false,
                            count = 0,
                            msg = "",
                        )
                        //todo：从数据库查聊天记录
//                        messageListItem.messageContentItems
                        homeViewModel.messageList.add(0, messageListItem)
                        Db.saveMsgList(messageListItem)//持久化
                        homeViewModel.msgListItemSelectId.value=messageListItem.id//选中
                    } else {
                        //存在
                        homeViewModel.msgListItemSelectId.value=existMessageListItem.id//选中
                    }
                    homeViewModel.leftMenuSelected.value= MenuItem.Chat
                    homeViewModel.column3ContentType.value=ContentType.FriendChat
                    homeViewModel.messageContentItemList.clear()
                    val messageListItem=homeViewModel.messageList.find { homeViewModel.msgListItemSelectId.value==it.id }
                    val index = homeViewModel.messageList.indexOf(messageListItem)
                    homeViewModel.messageList.remove(messageListItem)
                    messageListItem?.messageContentItems?.let { homeViewModel.messageContentItemList.addAll(it) }
                    homeViewModel.chatTitle.value = item.userName
                    messageListItem?.count = 0
                    messageListItem?.let { homeViewModel.messageList.add(index, it) }
                }
            ),
    ) {
        Row(
            modifier = Modifier.padding(start = 15.dp, top = 15.dp, bottom = 15.dp, end = 10.dp)
        ) {
            //头像
            NetworkImage(
                url = item.headUrl,
                painterFor = { remember { BitmapPainter(it) } },
                contentDescription = "头像",
                modifier = Modifier.size(51.dp).clip(CircleShape),
                contentScale = ContentScale.Crop,
                defaultPainterFor = painterResource("image/default_head.png")
            )
            Spacer(modifier = Modifier.width(10.dp))
            //用户名和在线状态和个性签名
            Column(modifier = Modifier.weight(1f).fillMaxHeight()) {
                //用户名
                Text(
                    text = item.userName,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    style = TextStyle(
                        color = Color.Black,
                        fontSize = 17.sp
                    )
                )
                Spacer(modifier = Modifier.weight(1f))
                Row {
                    //在线状态和
                    Text(
                        text = item.state,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        style = TextStyle(
                            color = Color(0xFF6F6F6F),
                            fontSize = 14.5.sp
                        )
                    )
                    Spacer(modifier = Modifier.width(10.dp))
                    //个性签名
                    Text(
                        text = item.personalSignature,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        style = TextStyle(
                            color = Color(0xFF6F6F6F),
                            fontSize = 14.5.sp
                        )
                    )
                }
            }
        }
    }
}